﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
//using ESMISProj.Business.Admin;
//using ESMISProj.Common;
using System.Reflection;
//using ESMISProj.Common.UISupports;
//using ESMISProj.Models.Admin;
//using zz.RestMVC.Contents;
//using zz.RestMVC.Filters;


using XM.PermissionFilter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace XM.PermissionFilter
{
    /// <summary>
    /// 权限拦截
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class PermissionFilterAttribute : FilterAttribute, IActionFilter
    {
        /// <summary>
        /// 是否忽略权限验证
        /// </summary>
        public bool IsIgnore { get; set; }
        /// <summary>
        /// 是否登录即可访问
        /// </summary>
        public bool IsLoginAccess { get; set; }
        /// <summary>
        /// 功能类型
        /// </summary>
        public PermissionType Type { get; set; }
        /// <summary>
        /// 系统管理员用户名
        /// </summary>
        public string SystemAdmin
        {
            get { return "admin"; }
        }

        /// <summary>
        /// 是否为系统功能
        /// </summary>
        public bool IsSystemApp { get; set; }

        //开始执行
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            #region 记录错误地址
            string domainName = filterContext.HttpContext.Request.Url.Authority;
            //获取 controllerName 名称
            string controllerName = filterContext.RouteData.Values["controller"].ToString();
            //获取ACTION 名称
            string actionName = filterContext.RouteData.Values["action"].ToString();
            HttpRequestBase bases = (HttpRequestBase)filterContext.HttpContext.Request;
            //获取url中的参数
            string queryString = bases.QueryString.ToString();
            //对获取到的参数进行UrlDecode处理
            queryString = HttpUtility.UrlDecode(queryString);
            string url = domainName + "/" + controllerName + "/" + actionName + "?" + queryString;
            url = "http://" + url;
            HttpContext.Current.Session["BackUrl"] = url;
            #endregion

            ////重新进入页面
            //filterContext.HttpContext.Response.Redirect("/Permission/Index");
            //return RedirectToAction("LoginW", "User");
            //timer = Stopwatch.StartNew();
            //logService.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            //    + "，客户请求："
            //    + filterContext.HttpContext.Request.RawUrl + "，开始");
        }
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            //timer.Stop();
            //logService.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            //    + "，客户请求："
            //    + filterContext.HttpContext.Request.RawUrl + "，结束，耗时：" + timer.Elapsed.TotalSeconds + "秒");
        }

        ///// <summary>
        ///// 权限验证
        ///// </summary>
        ///// <param name="methodName"></param>
        ///// <param name="controllerFullName"></param>
        ///// <returns></returns>
        //public override bool BeforeFilter(string methodName, string controllerFullName)
        //{
        //    //  Response.Write("对不起，[" + Request.Url.ToString() + "]，您权限不够访问！");

        //    bool isIgnored = IsIgnore; //权限拦截是否忽略
        //    if (isIgnored)
        //    {
        //        return true;
        //    }

        //    /*
        //     权限拦截代码
        //     */
        //    string userId;
        //    CacheSessionEntity cacheSessionEntity = null;
        //    try
        //    {
        //        cacheSessionEntity = ((CacheSessionEntity)
        //                              MvcRestContext.Current.Cache.Get(
        //                                  WebHelper.SessionUser(Request.Cookies[WebHelper.USERGUID])));
        //        userId = cacheSessionEntity.User.UserId;
        //        if (IsLoginAccess)
        //        {
        //            return true;
        //        }
        //    }
        //    catch (Exception ex)
        //    {

        //        userId = "";
        //    }
        //    //MvcRestContext.Current.Cache.Get(Request.Cookies[WebHelper.USERGUID]).ToString();


        //    if (userId == "")
        //    {
        //        Response.StatusCode = HttpStatusCode.Unauthorized;//401
        //        Response.Write("对不起，请先登录系统！");
        //        return false;
        //    }

        //    if (cacheSessionEntity != null && cacheSessionEntity.User.UserName == SystemAdmin)
        //    {
        //        return true;
        //    }
        //    var temp = controllerFullName.Split('.');

        //    string controller = temp[temp.Length - 1].Replace("Controller", "");
        //    string action = methodName;
        //    //数据库验证权限
        //    var sysMenuPermissionInRole = Sys_MenuPermissionInRoleBLL.CreateInstance();
        //    List<Sys_MenuPermissionInRole> menu = sysMenuPermissionInRole.QueryUserPermission(userId, controller,
        //                                                                                      action);
        //    if (menu.Count > 0)
        //    {
        //        return true;
        //    }
        //    Response.StatusCode = HttpStatusCode.Forbidden;//403
        //    Response.Write("对不起，[" + Request.Url.ToString() + "]，您权限不够访问！");
        //    return false;
        //}

        //public override void AfterFilter(object result, string methodName, string controllerFullName)
        //{
        //    var mn = methodName;
        //    var fn = controllerFullName;
        //    try
        //    {
        //        string userId =
        //           ((CacheSessionEntity)
        //            MvcRestContext.Current.Cache.Get(WebHelper.SessionUser(Request.Cookies[WebHelper.USERGUID]))).User
        //                                                                                                         .UserId;
        //    }
        //    catch (Exception ex)
        //    {//非正常访问

        //    }
        //    /*访问日志记录*/
        //}
        //public override void ErrorFilter(Exception ex, string methodName, string controllerFullName)
        //{
        //    base.ErrorFilter(ex, methodName, controllerFullName);
        //    /*错误日志记录*/
        //    string userId =
        //     ((CacheSessionEntity)
        //      MvcRestContext.Current.Cache.Get(WebHelper.SessionUser(Request.Cookies[WebHelper.USERGUID]))).User
        //                                                                                                   .UserId;
        //}

    }
    /// <summary>
    /// 权限类型
    /// </summary>
    public enum PermissionType
    {
        /// <summary>
        /// 按钮
        /// </summary>
        按钮 = 0,
        /// <summary>
        /// 页面请求
        /// </summary>
        页面 = 1,
        /// <summary>
        /// 普通请求
        /// </summary>
        普通 = 2,
        /// <summary>
        /// 数据操作请求
        /// </summary>
        数据 = 3
    }

    /// <summary>
    /// 允许静态页面跨域访问
    /// </summary>
    public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            base.OnActionExecuting(filterContext);
        }
    }
}